<template>
  <a-col :span="workSpaceItem.width || 24">
    <div class="chart-compt-wrapper protal-compt-wrapper" ref="chartArea">
      <a-card :bordered="false">
        <div slot="title" class="title">
          <span>{{ $t('portal.chart')}}</span><a-icon type="form" class="edit-btn" @click="openConfig" />
        </div>
        <div class="card-content-area">
          <div class="chart-box" ref="chartBox"></div>
        </div>
      </a-card>
      <chart-config-modal
        :visible="cfgModalStatus"
        :chartsCategory="chartsCategory"
        :currentChartCategoryId="currentChartCategoryId"
        :workSpaceItem="workSpaceItem"
        @ok="submitOK"
        @cancel="cancelModal"
        :getContainer="getContainer">
      </chart-config-modal>
    </div>
  </a-col>
</template>
<script>
// let dataTemp1 = [
//   {
//     name: '已完成',
//     color: '#e8c322',
//     label: ['需求管理', '产品型谱', '项目管理', '产品数据', '工艺管理'],
//     data: [120, 200, 150, 80, 70],
//   },
//   {
//     name: '未完成',
//     color: '#25cc74',
//     label: ['需求管理', '产品型谱', '项目管理', '产品数据', '工艺管理'],
//     data: [300, 100, 50, 40, 30],
//   }
// ]
import { getComponentDataList, getChartDataList } from '@/api/devportalApi.js'
import ChartConfigModal from './ChartConfigModal'
export default {
  name: 'Chart',
  data () {
    return {
      cfgModalStatus: false,
      chartsCategory: [],
      currentChartDataUrl: '',
      currentChartCategoryId: undefined
    }
  },
  props: {
    dataUrl: {
      type: String,
      defualt: ''
    },
    chartType: {
      type: String,
      defualt: 'bar'
    },
    workSpaceItem: {
      type: Object,
      defualt: () => ({})
    }
  },
  components: {
    ChartConfigModal
  },
  methods: {
    openConfig () {
      this.cfgModalStatus = true
    },
    drawChart (data) {
      let xLabel = data[0].label
      let series = data.map(item => {
        return {
          name: item.name,
          data: item.data,
          barWidth: 16,
          type: this.chartType,
          stack: 'one',//值一样的会堆叠
          itemStyle: {
            color: item.color ? item.color : '#ecaa00'
          }
        }
      })
      let myChart = this.$echarts.init(this.$refs.chartBox)
      let option = {
        grid: {
          top: 10,
          right: 10,
          bottom: 90
        },
        tooltip: {},
        // 图例小方块
        legend: {//文字默认取series的name
          bottom: 0,
          itemWidth: 12,
          itemHeight: 12,
        },
        xAxis: {
          type: 'category',
          data: xLabel,
          axisLine: {
            lineStyle: {//x轴线颜色
              color: '#dedede'
            }
          },
          axisLabel: {//x轴文字
            color: '#656565',
            interval: 0,
            fontSize: 10,
            formatter: function (value) {
              let str = ''
              value.split('').forEach((word, index) => {
                if ((index + 1) % 3 == 0) {
                  str += word + '\n'
                } else {
                  str += word
                }
              })
              return str
            }
          },
          axisTick: {//x轴刻度
            show: false
          }
        },
        yAxis: {
          type: 'value',
          axisLine: {
            show: false,
            lineStyle: {
              color: '#dedede'
            }
          },
          axisLabel: {
            color: '#656565'
          },
          axisTick: {
            show: false
          },
          splitLine: {
            lineStyle: {
              color: '#dedede'
            }
          }
        },
        series
      };
      // 使用刚指定的配置项和数据显示图表。
      myChart.setOption(option)
      window.onresize = function () {
        myChart.resize()
      }
    },
    parameterObj (parameterList) {
      let arr = parameterList.split(',')
      arr = arr.map(item => item.split('='))
      let propObj = {}
      for (let [key,val] of arr) {
        propObj[key] = val;
      }
      return propObj
    },
    async getData () {
      try {
        let res = await getComponentDataList(this.dataUrl)
        let content = res.data ? res.data.content : []
        content.sort((a, b) => a.rank - b.rank)
        this.chartsCategory = content
        if (this.workSpaceItem.personalConfig && this.workSpaceItem.personalConfig.contentSortList.length !== 0) {
          let currentPersonalConfigItem = this.workSpaceItem.personalConfig.contentSortList[0]
          this.currentChartCategoryId = currentPersonalConfigItem.contentId
          this.currentChartDataUrl = this.parameterObj(content.find(item => item.id == this.currentChartCategoryId).dataurl).dataUrl
        } else {
          this.currentChartCategoryId = content[0].id
          this.currentChartDataUrl = this.parameterObj(content[0] ? content[0].dataurl : '').dataUrl
        }
        let resChartData = await getChartDataList(this.currentChartDataUrl)
        this.drawChart(resChartData.data)
      } catch (error) {
        console.error(error)
      }
    },
    cancelModal () {
      this.cfgModalStatus = false
    },
    submitOK () {
      this.$emit('refreshPersonalConfig')
      this.cfgModalStatus = false
    },
    getContainer () {
      return this.$refs.chartArea
    }
  },
  mounted () {
    if (this.dataUrl) {
      this.getData()
    }
  },
  watch: {
    dataUrl (newUrl) {
      if (newUrl) {
        this.getData()
      }
    },
    chartType (newType) {
      if (newType) {
        this.getData()
      }
    },
    workSpaceItem: {
      handler: function () {
        this.getData()
      },
      deep: true
    }
  }
}
</script>
<style lang="less" scoped>
@import '~@/pages/devportal/modules/index.less';
.chart-box {
  min-height: 250px;
}
.chart-compt-wrapper {
  .card-content-area {
    height: 260px !important;
    overflow-x: visible !important;
    overflow-y: visible !important;
  }
}
</style>